﻿using AutoMapper;
using B.S.Warehouse.Domain.goods;
using B.S.Warehouse.ErrorCord;
using B.S.Warehouse.Read.Api.Application.Command.GoodsCommand;
using MediatR;
using SqlSugar;

namespace B.S.Warehouse.Read.Api.Application.Handelr.GoodsHandler
{
    public class GetGoodsHandler : IRequestHandler<GetGoodsCommand, ApiResult<ApiPaging<GoodsModel>>>
    {
        private readonly IMapper mapper;
        private readonly ISqlSugarClient db;

        public GetGoodsHandler(IMapper mapper, ISqlSugarClient db)
        {
            this.mapper = mapper;
            this.db = db;
        }

        public async Task<ApiResult<ApiPaging<GoodsModel>>> Handle(GetGoodsCommand request, CancellationToken cancellationToken)
        {
            ApiResult<ApiPaging<GoodsModel>> result = new ApiResult<ApiPaging<GoodsModel>>();
            var query = await db.Queryable<GoodsModel>().Where(x => !x.IsDel).ToListAsync();

            int totalCount = query.Count();
            int PageCount = (int)Math.Ceiling(totalCount * 1.0 / request.pageSize);
            query = query.OrderByDescending(a => a.GoodsModelId).Skip((request.pageindex - 1) * request.pageSize).Take(request.pageSize).ToList();
            ApiPaging<GoodsModel> paging = new ApiPaging<GoodsModel>()
            {
                totalCount = totalCount,
                PageCount = PageCount,
                Result = query.ToList(),
            };

            result.Code = ApiEnum.显示成功;
            result.MAG = ApiEnum.显示成功.ToString();
            result.data = paging;
            return result;
        }
    }
}
